package com.soledroid;

import java.io.*;
import java.net.*;
import java.util.*;

import android.app.*;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.*;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import org.json.*; 

import com.github.droidfu.widgets.WebImageView;
import com.soledroid.Model.Canteen;
import com.soledroid.Model.Stall;

public class CanteenActivity extends Activity {
	private LayoutInflater mInflater;
	
	protected String name;
	protected int id;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.canteen);
		mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
		
		id = getIntent().getExtras().getInt("id");
		name = getIntent().getExtras().getString("name");
		
		TextView mCanteenNameView = (TextView) findViewById(R.id.canteen_name);
		mCanteenNameView.setText(name);

		ImageView mCanteenImageView = (ImageView) findViewById(R.id.canteen_img);
		try {
			mCanteenImageView.setImageDrawable(Drawable.createFromStream(Utils.fetchImage("http://soledroid.huytoan.com/canteen/" + id + "/picture"), "src"));
		} catch (Exception e) {
			e.printStackTrace();
		} 
		
		final ArrayList<Stall> stalls = this.fetchStalls();
		
		CustomAdapter adapter = new CustomAdapter(this, R.layout.canteen_list_entry, R.id.canteen_stall_name, stalls);
		ListView lv = (ListView) findViewById((R.id.canteenListView));
		lv.setAdapter(adapter);

		lv.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent i = new Intent(getApplicationContext(), StallActivity.class); 

				Stall stall = stalls.get(position);
				i.putExtra("name", stall.getName());
				i.putExtra("id", stall.getId());
				i.putExtra("img_res", stall.getImage());

				CanteenActivity.this.startActivity(i);
			}
		});
	}
	
	public ArrayList<Stall> fetchStalls()
	{
		ArrayList<Stall> listItems = new ArrayList<Stall>();

		try {
			URL url = new URL("http://soledroid.huytoan.com/canteen/" + id + "/stalls");
			URLConnection tc = url.openConnection();
			tc.setUseCaches(true);
			BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));

			String line;
			while ((line = in.readLine()) != null) {
                JSONArray ja = new JSONArray(line);
 
                for (int i = 0; i < ja.length(); i++) {
                    JSONObject jo = (JSONObject) ja.get(i);
                    Stall stall = new Stall(jo.getInt("id"), jo.getString("name"), jo.getString("image"),
                    		jo.getString("description"), jo.getInt("canteen_id"));
                    listItems.add(stall);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } 
        return listItems;
    }
	
	
	private class CustomAdapter extends ArrayAdapter<Stall> {
		public CustomAdapter(Context context, int resource, int textViewResourceId, List<Stall> objects) {
			super(context, resource, textViewResourceId, objects);
		}
		
		@Override
	    public View getView(int position, View convertView, ViewGroup parent) {   
			ViewHolder holder = null;
			TextView stallNameView = null;
			TextView stallCountView = null;
			WebImageView stallImageView = null;
			Stall rowData = getItem(position);
			
			if(convertView == null) {
				convertView = mInflater.inflate(R.layout.canteen_list_entry, null);
				holder = new ViewHolder(convertView);
				convertView.setTag(holder);
			}

			holder = (ViewHolder) convertView.getTag();
			
			stallNameView = holder.getTitle();
			stallNameView.setText(rowData.getName());
			
			stallCountView = holder.getLikes();
			stallCountView.setText(rowData.getDescription());
			
			stallImageView = holder.getImage();
			if(rowData.getImage() == null) {
				//stallImageView.setImageResource(R.drawable.not_available);
			} else {
				try {
					stallImageView.setImageUrl(rowData.getImage());
					stallImageView.loadImage();
		        } catch (Exception e) {
		            e.printStackTrace();
		        }
			}

			return convertView;
		}
	}
	
	private class ViewHolder {
        private View mRow;
        private TextView mNameView = null;
        private TextView mCountView = null;
        private WebImageView mImageView = null; 
        
        public ViewHolder(View row) {
        	mRow = row;
        }
        
        public TextView getTitle() {
        	if(mNameView == null) {
        		mNameView = (TextView) mRow.findViewById(R.id.canteen_stall_name);
        	}
        	return mNameView;
        }  
        
        public TextView getLikes() {
        	if(mCountView == null) {
        		mCountView = (TextView) mRow.findViewById(R.id.canteen_stall_count);
        	}
        	return mCountView;
        }
        
        public WebImageView getImage() {
        	if(mImageView == null){
        		mImageView = (WebImageView) mRow.findViewById(R.id.canteen_stall_img);
        	}
        	return mImageView;
        }
	}
	
	 @Override
		public boolean onCreateOptionsMenu(Menu menu) {
			boolean result = super.onCreateOptionsMenu(menu);
			MenuInflater inflater = getMenuInflater();
			inflater.inflate(R.menu.menu, menu);
			return result;
		}
	    
	    @Override
		public boolean onOptionsItemSelected(MenuItem item) {
			Intent i;
			switch(item.getItemId()) {
			case R.id.menu_search:
				onSearchRequested();
				return true;
			case R.id.menu_preferences:
				showPreferences();
				return true;
			}
			return super.onOptionsItemSelected(item);
		}
	    
	    private void showPreferences() {
			Intent i = new Intent(this, SettingsActivity.class);
			startActivity(i);
		}

}
